package com.gimi.cloud.jimi.client.service.moreInfo.impl;

import com.gimi.cloud.jimi.client.service.moreInfo.ZmInfoService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoLogDao;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dto.app.moreInfo.MoreInfoDTO;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoLogEntity;
import com.gimi.cloud.jimi.entity.user.User;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @auther loongs
 * @date 2018/1/10  16:49
 */
@Service
public class ZmInfoServiceImpl implements ZmInfoService {
    private static Logger logger = LoggerFactory.getLogger(ZmInfoServiceImpl.class);
    private MoreInfoDao moreInfoDao;
    private SysConfigDao sysConfigDao;
    private InterfacePlatformRequestService requestService;
    private UserDao userDao;
    private MoreInfoLogDao moreInfoLogDao;

    private final String INTERFACE_PLATFORM_UNIVERSAL_ZMINFO = "interface_platform_universal_zminfo";
    //最大容错次数暂时定为3次
    private final Integer MAXTIMES = 3;

    @Autowired
    public ZmInfoServiceImpl(MoreInfoDao moreInfoDao, InterfacePlatformRequestService requestService, SysConfigDao sysConfigDao,
                             UserDao userDao, MoreInfoLogDao moreInfoLogDao) {
        this.moreInfoDao = moreInfoDao;
        this.requestService = requestService;
        this.sysConfigDao = sysConfigDao;
        this.userDao = userDao;
        this.moreInfoLogDao = moreInfoLogDao;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Response getZmInfo(MoreInfoDTO moreInfoDTO) throws Exception {
        Response response = new Response();
        User user = userDao.getUserByUserId(moreInfoDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过芝麻信用
        MoreInfoEntity moreInfoEntity = moreInfoDao.getMoreInfoByUserIdAndType(moreInfoDTO.getUserId(),1);
        if (moreInfoEntity != null && moreInfoEntity.getGetdataErrorTimes() >= MAXTIMES) {
            throw new MsgException(ResponseCodeEnum.ZM_DATA_ERROR_TIMES_IS_OUT_OF_TIMES);
        }
        //半段是不是新增，true是新增，false已存在
        boolean flag = false;

        //返回值为2的时候，是代表时间已经过期
        if (moreInfoEntity != null && (DateUtil.compare(moreInfoEntity.getReportEffectionEnd(), DateUtil.getNow()) == 2 ||
                (DateUtil.compare(moreInfoEntity.getReportEffectionEnd(), DateUtil.getNow()) == 0 && !"2".equals(moreInfoEntity.getGetdata())))) {
            //如果是有效期内，就做修改，不做新增
            //如果是失败的且过期时间为空，就需要做修改，不做新增
        } else {
            //时间过期了的新增
            moreInfoEntity = new MoreInfoEntity();
            moreInfoEntity.setGetdataTime(new Date());
            moreInfoEntity.setAnalysis("0");

            //user相关
            moreInfoEntity.setAddTime(new Date());
            moreInfoEntity.setAddUname(user.getAddUname());
            moreInfoEntity.setAddUid(user.getUserId());
            moreInfoEntity.setUserId(user.getUserId());

            //1芝麻信用
            moreInfoEntity.setDataType("1");
            moreInfoEntity.setGetdataMaxTimes(MAXTIMES);

            flag = true;
        }

        logger.info("获取芝麻信用评分开始");
        JSONObject config = JSONObject.fromObject(sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_ZMINFO));
        String param = config.getString("param").replace("#openId#", moreInfoDTO.getOpenId());
        logger.info("芝麻信用，请求参数：" + param);
        String result = requestService.sendApiPost(param);
        logger.info("芝麻信用，返回参数：" + result);
        String msg = null;
        JSONObject resultObject = JSONObject.fromObject(result);
        MoreInfoLogEntity moreInfoLogEntity = new MoreInfoLogEntity();
        //存入日志
        moreInfoLogEntity.setAddTime(DateUtil.getNow());
        moreInfoLogEntity.setResponseData(result);
        moreInfoLogEntity.setRequestData(param);
        moreInfoLogEntity.setUserId(user.getUserId());
        moreInfoLogEntity.setType("1");

        //--------------------------------2018.1.22修改，芝麻信用的json也提交到OSS--------------------------------------
        JSONObject reportBody= resultObject.getJSONObject("body");
        JSONObject reportHead= resultObject.getJSONObject("head");
        if(reportBody == null|| !"0".equals(reportHead.getString("status"))){
            throw new MsgException(ResponseCodeEnum.SERVICE_ERROR,reportHead.getString("responseDescription"));
        }
        JSONObject data=reportBody.getJSONObject("data");
        String type=reportBody.getString("type");

        //只有type为1的时候为成功，其他情况都是失败
        if ("1".equals(type)) {
            //TODO 有效时长，等风控规则
            moreInfoEntity.setReportEffectionBegin(DateUtil.getNow());
            moreInfoEntity.setReportEffectionEnd(DateUtil.getLateYear(1));
            moreInfoEntity.setGetdata("2");
            moreInfoEntity.setGetdataTime(DateUtil.getNow());
            moreInfoEntity.setGetdataErrorTimes(0);
            //存入数据
            moreInfoEntity.setReportData(data.getString("ossUrl"));
            moreInfoLogEntity.setStatus(1);
        }else {
            msg="获取失败!";
            moreInfoLogEntity.setStatus(2);
        }
        //-------------------------------------------------------------------------------------------------------------

        //如果获得分数失败，分别处理之前有记录和没记录的情况
        if (!"2".equals(moreInfoEntity.getGetdata())) {
            if (flag) {
                moreInfoEntity.setGetdataErrorTimes(1);
                moreInfoEntity.setGetdata("3");
                moreInfoDao.insertSelective(moreInfoEntity);
            } else {
                moreInfoEntity.setGetdataErrorTimes(moreInfoEntity.getGetdataErrorTimes() + 1);
                moreInfoEntity.setGetdata("3");
                moreInfoEntity.setUpdateUid(user.getUserId());
                moreInfoEntity.setUpdateUname(user.getAddUname());
                moreInfoEntity.setUpdateTime(DateUtil.getNow());
                moreInfoDao.updateByPrimaryKey(moreInfoEntity);
            }
            response.setResponseCode(ResponseCodeEnum.INTERFACE_ERROR, msg);
        } else {
            if (flag) {
                moreInfoDao.insertSelective(moreInfoEntity);
            } else {
                moreInfoEntity.setUpdateUid(user.getUserId());
                moreInfoEntity.setUpdateUname(user.getAddUname());
                moreInfoEntity.setUpdateTime(DateUtil.getNow());
                moreInfoDao.updateByPrimaryKey(moreInfoEntity);
            }
            response.setResponseCode(ResponseCodeEnum.SUCCESSED);
        }
        moreInfoLogDao.insertSelective(moreInfoLogEntity);
        logger.info("获取芝麻信用评分结束");
        return response;
    }
}
